import axios from 'axios'
import router from '../router/index'
import { getToken, removeToken } from '../util/auth'
// import Cookies from "js-cookie";
import { isProd } from './config' // 引入element loading 插件

axios.defaults.timeout = 20000
axios.defaults.baseURL = 'http://39.100.112.91:8888'
// isProd
//   ? 'http://101.200.42.104:27001'
//   : 'http://39.107.253.204:16066'
// axios.defaults.baseURL = isProd
//   ? 'http://101.200.42.104:27001'
//   : 'http://192.168.1.10:8885'

axios.interceptors.request.use(
  (config) => {
    config.headers = {
      'Content-Type': 'application/json;charset=utf-8',
      futureToken: getToken(),
    }
    if (config.url.indexOf('pay/v1/pay') > -1) {
      //http://education_continue.shgkpx.club 测试
      //http://official.test.shgkpx.net 生产
      config.baseURL = 'http://gkjyandy.ngrok2.xiaomiqiu.cn'
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  (response) => {
    if (response.data.code == 3004 || response.data.code == 3005) {
      removeToken()
      localStorage.removeItem('userInfo')
      return router.push('/login')
    }
    return response
  },
  (err) => {
    return Promise.reject(err.response.data)
  }
)

export function fetch(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params,
      })
      .then((response) => {
        resolve(response.data)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data).then(
      (response) => {
        resolve(response.data)
      },
      (err) => {
        reject(err)
      }
    )
  })
}

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data).then(
      (response) => {
        resolve(response.data)
      },
      (err) => {
        reject(err)
      }
    )
  })
}

// export default function({$axios, redirect, route, store}){
//   $axios.defaults.timeout = 20000
//   $axios.defaults.baseURL = false ? 'http://gateway.shgkpx.cn' : 'http://erp-test99.shgkpx.club:16006'

//   $axios.interceptors.request.use(
//     config => {
//       config.headers = {
//         'Content-Type': 'application/json;charset=utf-8',
//         'futureToken': store.state.user.data.token ? store.state.user.data.token : 'test'
//       }
//       return config
//     },
//     error => {
//         return Promise.reject(error)
//     }
//   )

//   $axios.interceptors.response.use(
//     response => {
//       // if(response.data.code == 404 || route.fullPath != '/login'){
//       //   redirect(`/login?path=${route.fullPath}`)
//       //   return
//       // }
//       return response;
//     },
//     err => {
//       return Promise.reject(err.response.data);
//     }
//   )
// }
